﻿using Kernelx.Contexts.Defaults;
using Newtonsoft.Json;
using System;
using System.Linq;

namespace Kernelx.Contexts.Newtonsoft
{

    /// <summary>
    /// 
    /// </summary>
    internal class DefaultJsonSerializer : IJsonSerializer
    {

        private readonly Formatting _formatting;
        private readonly JsonSerializerSettings _serializerSettings;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="formatting"></param>
        /// <param name="settings"></param> 
        public DefaultJsonSerializer(Formatting formatting, JsonSerializerSettings settings)
        {
            _formatting = formatting;
            _serializerSettings = settings;
            if (!_serializerSettings.Converters.Any(x => x is DictJsonConverter))
                _serializerSettings.Converters.Add(new DictJsonConverter());
        }


        /// <summary>
        /// 
        /// </summary>
        public DefaultJsonSerializer() : this(Formatting.None, new JsonSerializerSettings()) { }
         
        /// <summary>
        ///  <inheritdoc/> 
        /// </summary>
        /// <param name="json"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public object DeserializeObject(string json, Type type) => JsonConvert.DeserializeObject(json, type, _serializerSettings);
         
        /// <summary>
        ///  <inheritdoc/> 
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public string SerializeObject(object obj, Type type) => JsonConvert.SerializeObject(obj, type, _formatting, _serializerSettings);

    }
}
